package org.sdp.pearproject.config;

import org.sdp.pearproject.controller.MixRequestBody;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;

import javax.servlet.ServletRequest;

@Component
public class MixRequestMethodProcessor implements HandlerMethodArgumentResolver {

    private ServletModelAttributeMethodProcessor formResolver = null;
    private RequestResponseBodyMethodProcessor jsonResolver = null;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        MixRequestBody ann = parameter.getParameterAnnotation(MixRequestBody.class);
        return (ann != null);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        ServletRequest servletRequest = nativeWebRequest.getNativeRequest(ServletRequest.class);
        String contentType = servletRequest.getContentType();
        if (contentType == null) {
            throw new IllegalArgumentException("不支持contentType");
        }

        if (jsonResolver == null) {
            jsonResolver = new RequestResponseBodyMethodProcessor(MyWebMvcConfigurer.converters);
        }
        if (formResolver == null) {
            formResolver = new ServletModelAttributeMethodProcessor(true);
        }

        Object obj = null;
        if (contentType.contains("application/json")) {
            obj = jsonResolver.resolveArgument(methodParameter, modelAndViewContainer, nativeWebRequest, webDataBinderFactory);
        }

        if (contentType.contains("application/x-www-form-urlencoded")) {
            obj = formResolver.resolveArgument(methodParameter, modelAndViewContainer, nativeWebRequest, webDataBinderFactory);
        }

        if (contentType.contains("multipart")) {
            obj = formResolver.resolveArgument(methodParameter, modelAndViewContainer, nativeWebRequest, webDataBinderFactory);
        }
        if (obj != null) {
            return obj;
        }

        throw new IllegalArgumentException("不支持contentType");
    }
}